package com.nifostasky.comic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nifostasky.comic.entitys.CoDetailedInfo;
import com.nifostasky.comic.entitys.CoHomepageInfo;
import com.nifostasky.comic.exceptions.BusinessException;
import com.nifostasky.comic.mapper.CoHomepageInfoMapper;
import com.nifostasky.comic.query.CoHomepageInfoQuery;
import com.nifostasky.comic.service.CoDetailedInfoService;
import com.nifostasky.comic.service.CoHomepageInfoService;
import com.nifostasky.comic.service.CoSpiderInfoService;
import com.nifostasky.comic.service.ShellService;
import com.nifostasky.comic.vos.CoSpiderDetailedInfoVO;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 已爬取漫画信息关联表(CoHomepageInfo)表服务实现类
 *
 * @author makejava
 * @since 2022-02-14 21:09:41
 */
@Service("coHomepageInfoService")
public class CoHomepageInfoServiceImpl extends ServiceImpl<CoHomepageInfoMapper, CoHomepageInfo> implements CoHomepageInfoService {
    @Autowired
    private CoDetailedInfoService coDetailedInfoService;
    @Autowired
    private ShellService shellService;

    @Override
    public Map<String, Object> queryHomepageInfo(Integer pageIndex, Integer pageSize, CoHomepageInfoQuery query) {
        if (Objects.isNull(pageIndex)) pageIndex = 1;
        if (Objects.isNull(pageSize)) pageSize = 10;
        Map<String,Object> map = new HashMap<>();
        List<CoSpiderDetailedInfoVO> results = new ArrayList<>();
        Page<CoHomepageInfo> page = this.page(new Page<CoHomepageInfo>(pageIndex, pageSize), new QueryWrapper<CoHomepageInfo>().lambda()
                .eq(Objects.nonNull(query.getSpiderId()), CoHomepageInfo::getSpiderId, query.getSpiderId())
                .eq(Objects.nonNull(query.getType()), CoHomepageInfo::getType, query.getType())
                .orderByDesc(CoHomepageInfo::getCreateTime)
        );
        if (Objects.isNull(page.getRecords())) return null;
        page.getRecords().forEach(i -> {
            CoSpiderDetailedInfoVO result = new CoSpiderDetailedInfoVO();
            CoDetailedInfo detailedInfo = coDetailedInfoService.getById(i.getDetailedId());
            BeanUtils.copyProperties(detailedInfo,result);
            result.setSpiderId(i.getSpiderId());
            results.add(result);
        });
        map.put("total",page.getTotal());
        map.put("data",results);
        return map;
    }

    @Transactional
    @Override
    public Boolean saveTodayComicInfo(Long pyId) {
        Boolean exist = this.existTodayComic(pyId);
        if (exist)
            throw new BusinessException("python文件id为"+ pyId +"当天漫画信息以存在",-500);
        List<CoDetailedInfo> list = shellService.searchMainPageComic(pyId);
        list.stream().forEach(i -> {
            CoHomepageInfo coHomepageInfo = new CoHomepageInfo();
            coDetailedInfoService.save(i);
            coHomepageInfo.setSpiderId(pyId);
            coHomepageInfo.setDetailedId(i.getId());
            // 类型: 爬取的漫画
            coHomepageInfo.setType(0);
            coHomepageInfo.setCreateTime(new Date());
            this.save(coHomepageInfo);
        });
        return true;
    }

    /**
     * 检测当天的漫画信息是否存在,存在则不再爬取
     */
    private Boolean existTodayComic(Long pyId){
        LocalDate localDate = LocalDate.now();
        //查询今天pyId的信息是否存在
        Integer count = this.count(new QueryWrapper<CoHomepageInfo>().lambda()
                .eq(CoHomepageInfo::getSpiderId, pyId)
                .eq(CoHomepageInfo::getType, 0)
                .ge(CoHomepageInfo::getCreateTime,localDate)
                .lt(CoHomepageInfo::getCreateTime,localDate.plusDays(1))
        );
        return count > 0 ? true : false;
    }
}